package net.dreamlu.handler;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.dreamlu.kit.YUICompressorKit;

import org.apache.log4j.Logger;

import com.jfinal.handler.Handler;

/**
 * css js 压缩合并Handler
 * @author L.cm
 * @date 2013-7-2 上午10:51:46
 * <doc>使用示例:</doc>
 * <link rel="stylesheet" type="text/css" href="http://www.dreamlu.net/combo?/css/style.css,/css/index.css&v=0.0.1"></link>
 */
public class ComboHandler extends Handler {
    
    private static final Logger log = Logger.getLogger(ComboHandler.class);

    public void handle(String target, HttpServletRequest request,
            HttpServletResponse response, boolean[] isHandled) {
        // 拦截/combo 对css js 压缩
        if(target.endsWith("/combo")){
            isHandled[0] = true;
            String queryString = request.getQueryString();
            boolean isCss = true;
            if (queryString.indexOf(".js") > 0) {
                isCss = false;
            }
            if (isCss) {
                response.setContentType("text/css;charset=" + YUICompressorKit.CHARSET);
            }else {
                response.setContentType("text/javascript;charset=" + YUICompressorKit.CHARSET);
            }
            try {
                YUICompressorKit.compressorHelper(queryString, isCss, response.getWriter());
            } catch (IOException e) {
                log.error(e);
            }
            return;
        }else{
            // 执行后面的handle
            nextHandler.handle(target, request, response, isHandled);
        }
    }
}
